package com.flydog.mall.security;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * payload的格式（用户名、创建时间、生成时间）：
 * {"sub":"wang","created":1489079981393,"exp":1489684781}
 * signature的生成算法：
 * HMACSHA512(base64UrlEncode(header) + "." +base64UrlEncode(payload),secret)
 *
 * @author Cao
 * @description Jwt 生成和解析
 * @create 2021-04-08
 */
@Slf4j

public class JwtTokenUtil {

    @Value("${jwt.expiration}")
    private Long expiration;

    private static final String SECRET = "caoweidong1982@126.com";

    private static final String CLAIM_KEY_USERNAME = "sub";
    private static final String CLAIM_KEY_CREATED = "created";


    /**
     * 根据用户信息生成Token
     *
     * @param userDetails 用户信息
     * @return Token字符串
     */
    public String generateToken(UserDetails userDetails) {
        HashMap<String, Object> claims = new HashMap<>(2);
        claims.put(CLAIM_KEY_CREATED, new Date());
        claims.put(CLAIM_KEY_USERNAME, userDetails.getUsername());
        return generateTokenByClaim(claims);
    }

    /**
     * 根据用户信息生成Token
     *
     * @param userName 用户名称
     * @return Token字符串
     */
    public String generateToken(String userName) {
        HashMap<String, Object> claims = new HashMap<>(2);
        claims.put(CLAIM_KEY_CREATED, new Date());
        claims.put(CLAIM_KEY_USERNAME, userName);
        return generateTokenByClaim(claims);
    }

    /**
     * 从token中获取用户名
     *
     * @param token token字符串
     * @return 用户名
     */
    public String getUserNameFromToken(String token) {
        String userName = null;
        Claims claims = getClaimsFromToken(token);
        userName = claims.getSubject();
        return userName;
    }

    /**
     * 验证token是否有效
     *
     * @param token       token字符串
     * @param userDetails 用户信息
     * @return 是否有效
     */
    public boolean validateToken(String token, UserDetails userDetails) {
        String userName = getUserNameFromToken(token);
        return userDetails.getUsername().equals(userName) && !isTokenExpired(token);
    }

    /**
     * 使用Map构建Token
     *
     * @param claims Token的payload
     * @return Token字符串
     */
    private String generateTokenByClaim(Map<String, Object> claims) {
        return Jwts.builder()
                .setClaims(claims)
                .setExpiration(generateExpirationDate())
                .signWith(SignatureAlgorithm.HS512, SECRET)
                .compact();
    }

    /**
     * 为Token生成过期时间
     *
     * @return 生成的过期时间
     */
    private Date generateExpirationDate() {
        return new Date(System.currentTimeMillis() + expiration * 1000);
    }

    /**
     * 从token中解析负载
     * @param token token字符串
     * @return token载荷
     */
    private Claims getClaimsFromToken(String token) {
        Claims claims = null;
        try {
            claims = Jwts.parser()
                    .setSigningKey(SECRET)
                    .parseClaimsJws(token)
                    .getBody();
        } catch (Exception e) {
            log.info("解析Token{}错误", token);
        }
        return claims;
    }

    /**
     * 判断token是否过期
     * @param token token字符串
     * @return 是否过期
     */
    private boolean isTokenExpired(String token) {
        Date expiredTime = getClaimsFromToken(token).getExpiration();
        return expiredTime.before(new Date());
    }
}
